package com.dmz.flink;


import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.Operator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class BatchWordCount {

    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        //todo read data from files
        DataSource<String> dataSource = env.readTextFile("E:\\IdeaProjects\\flinkTutorial\\src\\main\\java\\com\\dfjx\\flinkTuorial\\wordCount\\input\\hello.txt");
        Operator dataOperator = env.readTextFile("E:\\IdeaProjects\\flinkTutorial\\src\\main\\java\\com\\dfjx\\flinkTuorial\\wordCount\\input\\hello.txt");
        DataSet<String> dataSet = env.readTextFile("E:\\IdeaProjects\\flinkTutorial\\src\\main\\java\\com\\dfjx\\flinkTuorial\\wordCount\\input\\hello.txt");
        /**
         * the relations for class DataSource, Operator, DataSet
         * DataSource extends abstract Operator
         * Operator extends abstract    DataSet
         */

        //todo string =>> (word,1)
        AggregateOperator<Tuple2<String, Integer>> dataSourceSum = dataSource.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(new Tuple2<>(word, 1));
                }
            }
        }).groupBy(0).sum(1);
        dataSourceSum.print("dataSourceSum: ");

        AggregateOperator dataOperatorSum = dataOperator.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(new Tuple2<>(word, 1));
                }
            }
        }).groupBy(0).sum(1);
        dataOperatorSum.print("dataOperatorSum: ");

        AggregateOperator<Tuple2<String, Integer>> dataSetSum = dataSet.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(new Tuple2<>(word, 1));
                }
            }
        }).groupBy(0).sum(1);
        dataSetSum.print("dataSetSum: ");

        env.execute();
    }
}